package com.yhyvr.api.service.file;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.media.MediaConfiguration;
import com.alibaba.media.MediaException;
import com.alibaba.media.upload.UploadPolicy;
import com.alibaba.media.upload.UploadTokenClient;
import com.alibaba.media.upload.impl.DefaultUploadTokenClient;
import com.google.common.collect.Lists;
import com.lz.kit.LogKit;
import com.lz.kit.ehcache.CacheKit;
import com.lz.mybatis.jdbc.auto.model.SysFile;
import com.lz.tool.FileTool;
import com.yhyvr.pojo.exception.ApiException;
import com.yhyvr.api.handle.AuthAnnotation;
import com.yhyvr.pojo.req.api.ApiReqBody;
import com.yhyvr.pojo.req.api.ApiReqData;
import com.yhyvr.pojo.resp.api.ApiRespData;
import com.yhyvr.pojo.resp.api.ApiResultCode;
import com.yhyvr.service.UploadService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by tech6 on 2016/10/20.
 */

@Service
public class FileUploadService {
    @Resource
    private UploadService uploadService;
    /**
     * 单文件上传需要登录
     * @param apiReqBodyApiReqData
     * @return
     */
    @AuthAnnotation(iLogin = true)
    public ApiRespData<SysFile> uploadLogin(ApiReqData<ApiReqBody> apiReqBodyApiReqData){
        return upload(apiReqBodyApiReqData);
    }
    /**
     * 单文件上传
     * @param apiReqBodyApiReqData
     * @return
     */
    public ApiRespData<SysFile> upload(ApiReqData<ApiReqBody> apiReqBodyApiReqData){
        try{
            HttpServletRequest request =apiReqBodyApiReqData.getHead().getHttpServletRequest();
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求@RequestParam MultipartFile file
            if(multipartResolver.isMultipart(request)) {
                //转换成多部分request
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                Iterator<String> fileNames = multipartRequest.getFileNames();
                String fileName = fileNames.next();
                MultipartFile uploadFile = multipartRequest.getFile(fileName);
                if (uploadFile == null) {
                    throw new ApiException("没有找到附件",0,apiReqBodyApiReqData.getHead().getCrossDomain());
                } else {
                    String ext = FileTool.getExtention(uploadFile.getOriginalFilename());
                    if(uploadFile.getContentType().equals("image/jpeg")){
                        if(ext.length()==0){
                            ext=".png";
                        }
                    }
                    if(ext.toLowerCase().equals(".jpg")||ext.toLowerCase().equals(".png")){
                        SysFile sysFile = uploadService.uploadToAli(uploadFile);
                        return ApiRespData.buildSucc(sysFile);
                    }else{
                        throw new ApiException("上传格式错误，仅仅支持.jpg .png",0,apiReqBodyApiReqData.getHead().getCrossDomain());
                    }

                }
            }else{
                throw new ApiException("请求方式不正确",0,apiReqBodyApiReqData.getHead().getCrossDomain());
            }
        }catch(Exception e){
            LogKit.error(e.getMessage(),e);
            throw new ApiException(e.getMessage(),0,apiReqBodyApiReqData.getHead().getCrossDomain());
        }
    }

    /**
     * 多文件上传
     * @param apiReqBodyApiReqData
     * @return
     */
    public ApiRespData<List<SysFile>> uploadMu(ApiReqData<ApiReqBody> apiReqBodyApiReqData){

            HttpServletRequest request =apiReqBodyApiReqData.getHead().getHttpServletRequest();
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求
            if(multipartResolver.isMultipart(request)) {
                //转换成多部分request
                MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
                Iterator<String> fileNames = multipartRequest.getFileNames();
                List<SysFile> list = Lists.newArrayList();
                while (fileNames.hasNext()){
                    try {
                String fileName = fileNames.next();
                MultipartFile uploadFile = multipartRequest.getFile(fileName);
                if (uploadFile == null) {
                    throw new ApiException("没有找到附件",0,apiReqBodyApiReqData.getHead().getCrossDomain());
                } else {
                  //  String serverPath = File.separator + "upload" + File.separator + DateUtil.DateToString(new Date(), DateStyle.YYYYMMDD);
                    String ext = FileTool.getExtention(uploadFile.getOriginalFilename());
                    if (uploadFile.getContentType().equals("image/jpeg")) {
                        if (ext.length() == 0) {
                            ext = ".png";
                        }
                    }
                    if (ext.toLowerCase().equals(".jpg") || ext.toLowerCase().equals(".png")) {
                   //     String name = System.nanoTime() + ext;
                        SysFile sysFile = null;
                        sysFile = uploadService.uploadToAli(uploadFile);
                        list.add(sysFile);
                    } else {
                        throw new ApiException("上传格式错误，仅仅支持.jpg .png", 0, apiReqBodyApiReqData.getHead().getCrossDomain());
                    }
                  }
                    } catch (IOException e) {
                       LogKit.error(e.getMessage(),e);
                        continue;
                    }
                }
                return ApiRespData.buildSucc(list);
            }else{
                throw new ApiException("请求方式不正确",0,apiReqBodyApiReqData.getHead().getCrossDomain());
            }

    }


            public ApiRespData<JSONObject> getBaiChuanToken(ApiReqData<ApiReqBody> apiReqBodyApiReqData){
                JSONObject jsonObject = new JSONObject();
                    if(CacheKit.get("aliToken","aliToken")!=null){
                        jsonObject.put( "token", CacheKit.get("aliToken","aliToken") );
                    }else {
                        try {
                        //1. 定义全局配置信息
                        MediaConfiguration configuration = new MediaConfiguration();
                        configuration.setAk("23395592"); //用户控制台的AccessKey
                        configuration.setSk("ea0518b58d290b16060cbb8c9390d7d0"); //用户控制台的AccessSecret
                        configuration.setNamespace("arbanban"); //用户的空间名namespace

                        // 2. 获取凭证Client
                        UploadTokenClient tokenClient = new DefaultUploadTokenClient(configuration);

                        // 3. 定义上传策略
                        UploadPolicy uploadPolicy = new UploadPolicy();
                        uploadPolicy.setInsertOnly(UploadPolicy.INSERT_ONLY_NONE); //INSERT_ONLY_NONE=0表示可覆盖上传，INSERT_ONLY=1表示不可覆盖
                        uploadPolicy.setExpiration(System.currentTimeMillis() + 3600 * 1000); //token过期时间，单位毫秒。-1表示永不过期。
                        // 4. 获取上传Token
                        String token = tokenClient.getUploadToken(uploadPolicy);
                        CacheKit.put("aliToken", "aliToken", token);
                        // 5. 输出
                        jsonObject.put("token", token);
                    } catch (MediaException e) {
                        return ApiRespData.buildFailErrorCode(ApiResultCode.FAIL,e.getMessage());
                    }
                    }

                return ApiRespData.buildSucc(jsonObject);
            }

}
